<?php
/** 
 * 权限分组模型扩展类
 *
 * @author   xg
 * @date     2019-09-20
 */

namespace app\auth\model;

use think\Db;
use think\Model;
use think\facade\Log;
use app\common\model\AuthGroup;

class AuthGroupModel extends AuthGroup
{

    /**
     * 获取规则列表
     * @param   array   $params     筛选条件
     * @return  array   规则数据
     */
    public function getList($params)
    {
        $model  = $this;
        $page   = $params['page'] > 0 ? $params['page'] : 1;
        $limit  = $params['limit'] > 0 ? $params['limit'] : 15;

        if (!empty($params['keyword'])) {
            $model = $model->where("name LIKE '%".$params['keyword']."%'");
        }

        $count  = $model->count();
        $data   = $model->limit($limit)->page($page)->select();
        $result = [
            'status_map'    => $this->getStatusMap(),
            'group_tree'    => $this->getGroupTree(),
        ];

        krsort($result['status_map']);

        $result['total']    = 0;
        $result['list']     = $data;
        return $result;
    }

    /**
     * 获取分组树
     * @param   number  $rule_id    规则id
     * @return  array   规则数据
     */
    public function getGroupTree($group_id='')
    {
        $data = $this->select();

        if ($data->isEmpty()) {
            return;
        }

        foreach ($data->toArray() as $value) {
            $group_map[$value['group_id']] = [
                'group_id'  => $value['group_id'],
                'pid'       => $value['pid'],
                'name'      => $value['name'],
                'rules'     => $value['rules'],
                'status'    => $value['status'],
                'child'     => [],
            ];
        }

        foreach ($group_map as $key => $value) {
            if ($value['pid'] > 0) {
                $group_map[$value['pid']]['child'][] = &$group_map[$key];
            }
        }

        foreach ($group_map as $key => $value) {
            if (!empty($group_id) && $group_id == $key) {
                return $value;
            }

            if($value['pid'] > 0){
                unset($group_map[$key]);
                continue;
            }

            $result[] = $value;
        }
        
        return $result;
    }

    /**
     * 添加分组
     * @param   array   $params     规则数据
     * @return  array   规则数据
     */
    public function addOne($params)
    {
        $this->checkUpdate($params);

        if (!empty($this->error)) {
            return;
        }

        $params['rules'] = implode(',', $params['rules']);
        $params['create_time'] = time();

        try {
            $this->create($params);
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
        }
    }

    /**
     * 修改分组
     * @param   array   $params     分组数据
     * @return  array   分组数据
     */
    public function editOne($params)
    {
        $group_id = $params['group_id'];
        $record = $this->where(['group_id' => $params['group_id']])->find();

        if (empty($record)) {
            $this->error = '规则不存在';
            return;
        }

        foreach ($params as $key => $value) {
            if ($value == $record[$key]) {
                unset($params[$key]);
            }
        }

        if (empty($params)) {
            return;
        }

        $this->checkUpdate($params);

        if (!empty($this->error)) {
            return;
        }

        try {
            $params['rules'] = implode(',', $params['rules']);
            $params['update_time'] = time();
            $this->where('group_id = '.$group_id)->update($params);
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
        }
    }

    /**
     * 删除分组
     * @param   array   $params     分组数据
     * @return  array   分组数据
     */
    public function delOne($params)
    {
        $record = $this->where(['group_id' => implode(',', $params['group_id'])])->select();

        if ($record->isEmpty()) {
            $this->error = '规则不存在';
            return;
        }

        $self = $this;
        $delRule = function ($tree) use ($self, &$delRule) {
            if (!empty($tree['child'])) {
                foreach ($tree['child'] as $value) {
                    $delRule($value);
                }  
            }
            $this->where(['group_id' => $tree['group_id']])->delete();
        };
        
        try {
            foreach ($record as $value) {
                $tree = $this->getGroupTree($value['group_id']);
                $delRule($tree);
            }
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
        }
    }

    /**
     * 添加、修改规则数据基本检测
     * @param   array   $params     规则数据
     * @return  mixed
     */
    private function checkUpdate($params)
    {
        if (!empty($params['name'])) {
            $record = $this->where("name = '".$params['name']."'")->find();

            if (!empty($record)) {
                $this->error = '分组名已存在';
                return;
            }
        }

        return true;
    }

}
